package com.fling.abcde.base;

import static com.fling.abcde.BaseApplication.sToken;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.FragmentActivity;
import androidx.viewbinding.ViewBinding;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.fling.abcde.R;
import com.fling.abcde.databinding.ActivityBaseBinding;
import com.lib.common.view.ImageTextView;
import com.lib.okhttp.NetClient;
import com.lib.common.bean.BaseResp;
import com.lib.utils.ConvertUtils;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class BaseActivity<T extends ViewBinding> extends FragmentActivity implements NetClient.IDataChangeListener {
    protected ActivityBaseBinding baseBinding;
    protected T thisBinding;

    protected NetClient mNetManager = new NetClient(this);

    private int baseActionBarColor;
    private boolean mCanTranslucent;
    private boolean mAllowSetContentView;

    public static void start(Activity activity, Class<?> clazz) {
        Intent intent = new Intent(activity, clazz);
        activity.startActivity(intent);
    }

    public BaseActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initWindow();
        initViewBinding();

        baseActionBarColor = getResources().getColor(R.color.theme_color);
        // Integer resId = getResources().getIdentifier(string.replace("R.drawable.", ""),
        // 	"drawable", getPackageName());
    }

    private void initWindow() {
        if (Build.VERSION.SDK_INT >= 19) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // Translucent navigation bar
            // window.setFlags(
            // 	WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
            // 	WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            mCanTranslucent = true;
        } else {
            mCanTranslucent = false;
            baseBinding.baseStatusBar.setVisibility(View.GONE);
        }
    }

    private void initViewBinding() {
        LayoutInflater inflater = getLayoutInflater();
        baseBinding = ActivityBaseBinding.inflate(inflater);
        baseBinding.baseActionBarLeft.setOnClickListener(v -> onBaseLeftClicked());
        baseBinding.baseActionBarCenter.setOnClickListener(v -> onBaseCenterClicked());
        baseBinding.baseActionBarRight.setOnClickListener(v -> onBaseRightClicked());

        Type superclass = getClass().getGenericSuperclass();
        if (superclass != null) {
            if (superclass instanceof ParameterizedType) {
                //获得父类的泛型参数的实际类型
                Type[] actualTypeArguments = ((ParameterizedType) superclass).getActualTypeArguments();
                Class<?> clz = (Class<?>) actualTypeArguments[0];
                try {
                    //获取inflate方法 传入相应的参数
                    Method method = clz.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                    method.setAccessible(true);
                    //执行inflate方法
                    thisBinding = (T) method.invoke(null, inflater, null, false);
                } catch (Throwable e) {
                    e.printStackTrace();
                }

                if (thisBinding != null) {
                    View view = thisBinding.getRoot();
                    baseBinding.baseContent.addView(view);
                }
                mAllowSetContentView = false;
                super.setContentView(baseBinding.getRoot());
            } else {
                mAllowSetContentView = true;
            }
        }
    }

    protected void onBaseLeftClicked() {

        onBackPressed();
    }

    protected void onBaseCenterClicked() {

    }

    protected void onBaseRightClicked() {

    }

    public ViewGroup getDecorView() {

        return (ViewGroup) getWindow().getDecorView();
    }

    /**
     * @return 状态栏的高度 单位 px，err return -1
     */
    private int getStatusBarHeight() {

        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    public void setFullScreenTranslucent(boolean isFullScreen) {

        if (isFullScreen) {
            baseBinding.baseActionBar.setVisibility(View.GONE);
            baseBinding.baseActionBar.setVisibility(View.GONE);
        } else {
            if (mCanTranslucent) {
                baseBinding.baseStatusBar.setVisibility(View.VISIBLE);
            }
            baseBinding.baseActionBar.setVisibility(View.VISIBLE);
        }
    }

    public void setFullScreen(boolean isFullScreen) {

        if (isFullScreen) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    /**
     * @param isShow true is Show the Actionbar
     */
    public void setActionBarVisible(boolean isShow) {

        if (isShow) {
            baseBinding.baseActionBar.setVisibility(View.VISIBLE);
        } else {
            baseBinding.baseActionBar.setVisibility(View.GONE);
        }
    }

    /**
     * @param isShow true is Show the Leftback
     */
    public void setActionBarLeftVisible(boolean isShow) {

        if (isShow) {
            baseBinding.baseActionBarLeft.setVisibility(View.VISIBLE);
        } else {
            baseBinding.baseActionBarLeft.setVisibility(View.GONE);
        }
    }

    /**
     * @param isShow true is Show the Leftback
     */
    public void setActionBarRightVisible(boolean isShow) {

        if (isShow) {
            baseBinding.baseActionBarRight.setVisibility(View.VISIBLE);
        } else {
            baseBinding.baseActionBarRight.setVisibility(View.GONE);
        }
    }

    public ViewGroup getActionBarView() {

        return baseBinding.baseActionBar;
    }

    /**
     * 设置动作栏高度，
     *
     * @param height 单位 dp
     */
    public void setActionBarHeight(int height) {

        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        height = ConvertUtils.dp2px(this, height);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
        baseBinding.baseActionBar.setLayoutParams(params);
    }

    /**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     * @see #setContentView(View)
     * @see #setContentView(View, ViewGroup.LayoutParams)
     */
    @Override
    public void setContentView(int layoutResID) {

        if (mAllowSetContentView) {
            baseBinding.baseContent.removeAllViews();
            /*  baseBinding.baseContent.addView(View.inflate(this, layoutResID, null)); 会丢弃父容器的属性，i.g.margin */
            LayoutInflater.from(this).inflate(layoutResID, baseBinding.baseContent);
            super.setContentView(baseBinding.getRoot());
        }
    }

    /**
     * Convenience for
     * {@link #setContentView(View, ViewGroup.LayoutParams)}
     * set the screen content to an explicit view.  This view is placed
     * directly into the screen's view hierarchy.  It can itself be a complex
     * view hierarhcy.
     *
     * @param view The desired content to display.
     * @see #setContentView(View, ViewGroup.LayoutParams)
     */
    public void setContentView(View view) {

        if (view != null) {
            baseBinding.baseContent.removeAllViews();
            baseBinding.baseContent.addView(view);
        }
        super.setContentView(baseBinding.getRoot());
    }

    /**
     * Set the activity content to an explicit view.  This view is placed
     * directly into the activity's view hierarchy.  It can itself be a complex
     * view hierarchy.
     *
     * @param view   The desired content to display.
     * @param params Layout parameters for the view.
     * @see #setContentView(View)
     * @see #setContentView(int)
     */
    public void setContentView(View view, ViewGroup.LayoutParams params) {

        baseBinding.baseContent.removeAllViews();
        baseBinding.baseContent.addView(view);
        super.setContentView(baseBinding.getRoot(), params);
    }

    /**
     * @param view The desired content to add ,default in center.
     */
    public void addContentView(View view) {

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        addContentView(view, params);
    }

    /**
     * @param view   The desired content to add.
     * @param params layout LayoutParams
     */
    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {

        baseBinding.baseContent.addView(view, params);
        super.setContentView(baseBinding.getRoot());
    }

    /**
     * 设置ActionBar的颜色
     *
     * @param argb 16进制颜色值，i.g.0xFFxxx
     */
    public void setActionBarColor(int argb) {

        baseBinding.baseStatusBar.setBackgroundColor(argb);
        baseBinding.baseActionBar.setBackgroundColor(argb);
        baseActionBarColor = argb;
    }

    @Override
    public void setTitle(CharSequence title) {

        setTitle(title.toString());
    }

    public void setTitle(String title) {

        baseBinding.baseActionBarCenter.setText(ImageTextView.TEXT_TOP, title);
    }

    public void showLoading() {

        baseBinding.loadingLayer.setVisibility(View.VISIBLE);
    }

    public void showLoading(String tip) {

        baseBinding.loadingLayer.setVisibility(View.VISIBLE);
        baseBinding.loadingTv.setText(tip);
    }

    public void hideLoading() {
        baseBinding.loadingLayer.setVisibility(View.GONE);
    }

    public boolean isLoading() {
        return baseBinding.loadingLayer.isShown();
    }

    @Override
    public void onDataChanged(BaseResp baseResp) {

        if (baseResp.getCode() == 333) {
            if (sToken != null) {
                showOtherLogin();
            }
            hideLoading();
        }
    }

    @Override
    public void onProgressChanged(Integer progress) {

    }

    public void showOtherLogin() {
/*
        sUser.setToken(null);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_show_other_login, getDecorView(), false);
        TextView showcomfirm = view.findViewById(R.id.show_comfirm);
        TextView showquit = view.findViewById(R.id.show_quit);
      showquit.setOnClickListener(v -> {

            mPopLayer.setVisibility(View.GONE);
            finish();
        });
        showcomfirm.setOnClickListener(v -> {

            mPopLayer.setVisibility(View.GONE);
//            LoginActivity.start(this);
        });
        showPopLayer(view);*/
    }

    @Override
    public void onBackPressed() {
        //
        // Toast.makeText(getApplicationContext(), "再次点击,将退出程序！", Toast.LENGTH_SHORT).showLoading();
        //
        // long l = System.currentTimeMillis();
        // if ((l - exitTime) > 2000) {
        // 	exitTime = l;
        // } else {
        super.onBackPressed();
//    }
    }

    @Override
    protected void onDestroy() {
        baseBinding = null;
        thisBinding = null;

        mNetManager.onDestroy();
        super.onDestroy();
    }
}